package com.accounting.ui;

import com.accounting.model.*;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.geometry.Insets;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.time.LocalDate;
import com.accounting.util.ExportUtil;
import javafx.stage.Stage;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.geometry.Pos;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import com.accounting.db.DatabaseManager;
import java.sql.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.geometry.Orientation;
import com.accounting.util.ConfigManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javafx.stage.FileChooser;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeItem;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.ComboBox;
import javafx.util.StringConverter;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextArea;
import javafx.scene.control.CheckBox;
import javafx.event.ActionEvent;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicReference;
import com.accounting.model.AssetIncome;
import com.accounting.model.AssetIncomeDetail;
import javafx.scene.control.Tooltip;
import java.util.ArrayList;
import javafx.scene.chart.PieChart;
import java.util.HashMap;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Cell;

public class MainView {
    private BorderPane root;
    private TableView<Transaction> transactionTable;
    private ObservableList<Transaction> transactions;
    private String currentUsername;
    private Label totalAssetsLabel;
    private Label totalLiabilitiesLabel;
    private Label netWorthLabel;
    private ObservableList<Transaction> incomeTransactions;
    private ObservableList<Transaction> expenseTransactions;
    private VBox content;  // 添加这一行

    public MainView(String username) {
        this.currentUsername = username;
        root = new BorderPane();
        initializeTable();
        createContent();
        refreshTransactionTable();
    }

    private void initializeTable() {
        transactionTable = new TableView<>();
        transactions = FXCollections.observableArrayList();
        
        // 日期列
        TableColumn<Transaction, LocalDate> dateCol = new TableColumn<>("日期");
        dateCol.setCellValueFactory(new PropertyValueFactory<>("date"));
        dateCol.setPrefWidth(100);
        
        // 类型列
        TableColumn<Transaction, String> typeCol = new TableColumn<>("类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("type"));
        typeCol.setPrefWidth(80);
        
        // 类别列
        TableColumn<Transaction, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        categoryCol.setPrefWidth(100);
        
        // 账户列（修改为显示用户名）
        TableColumn<Transaction, String> userCol = new TableColumn<>("账户");
        userCol.setCellValueFactory(new PropertyValueFactory<>("assetName"));
        userCol.setPrefWidth(100);
        
        // 金额列
        TableColumn<Transaction, Double> amountCol = new TableColumn<>("金额");
        amountCol.setCellValueFactory(new PropertyValueFactory<>("amount"));
        amountCol.setPrefWidth(100);
        amountCol.setCellFactory(col -> new TableCell<Transaction, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                    // 设置金额颜色：收入为绿色，支出为红色
                    Transaction transaction = getTableRow().getItem();
                    if (transaction != null) {
                        if ("支出".equals(transaction.getType())) {
                            setTextFill(Color.RED);
                        } else {
                            setTextFill(Color.GREEN);
                        }
                    }
                }
            }
        });
        
        // 描述列
        TableColumn<Transaction, String> descCol = new TableColumn<>("描述");
        descCol.setCellValueFactory(new PropertyValueFactory<>("description"));
        descCol.setPrefWidth(200);
        
        transactionTable.getColumns().addAll(
            dateCol, typeCol, categoryCol, userCol, amountCol, descCol
        );
        
        transactionTable.setItems(transactions);
        refreshRecentTransactions();
    }

    private void setupTransactionTable(TableView<Transaction> table, ObservableList<Transaction> data) {
        // 日期列
        TableColumn<Transaction, LocalDate> dateCol = new TableColumn<>("日期");
        dateCol.setCellValueFactory(new PropertyValueFactory<>("date"));
        dateCol.setPrefWidth(100);
        
        // 类型列
        TableColumn<Transaction, String> typeCol = new TableColumn<>("类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("type"));
        typeCol.setPrefWidth(80);
        
        // 类别列
        TableColumn<Transaction, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        categoryCol.setPrefWidth(100);
        
        // 账户列
        TableColumn<Transaction, String> accountCol = new TableColumn<>("账户");
        accountCol.setCellValueFactory(new PropertyValueFactory<>("assetName"));
        accountCol.setPrefWidth(120);
        
        // 金额列
        TableColumn<Transaction, Double> amountCol = new TableColumn<>("金额");
        amountCol.setCellValueFactory(new PropertyValueFactory<>("amount"));
        amountCol.setPrefWidth(100);
        amountCol.setCellFactory(col -> new TableCell<Transaction, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                    // 设置金额颜色：收入为绿色，支出为红色
                    Transaction transaction = getTableRow().getItem();
                    if (transaction != null) {
                        if ("支出".equals(transaction.getType())) {
                            setTextFill(Color.RED);
                        } else {
                            setTextFill(Color.GREEN);
                        }
                    }
                }
            }
        });
        
        // 描述列
        TableColumn<Transaction, String> descCol = new TableColumn<>("描述");
        descCol.setCellValueFactory(new PropertyValueFactory<>("description"));
        descCol.setPrefWidth(200);
        
        // 设置列
        table.getColumns().addAll(
            dateCol, typeCol, categoryCol, accountCol, amountCol, descCol
        );
        
        // 设置数据
        table.setItems(data);
    }

    private void createContent() {
        // 创建顶部菜单栏
        MenuBar menuBar = createMenuBar();
        root.setTop(menuBar);

        // 创建左侧导航栏
        VBox leftPanel = createLeftPanel();
        root.setLeft(leftPanel);

        // 默认显示总览
        showOverview();
    }

    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        
        // 文件菜单
        Menu fileMenu = new Menu("文件");
        MenuItem exportItem = new MenuItem("导出数据");
        MenuItem importItem = new MenuItem("导入数据");
        MenuItem logoutItem = new MenuItem("退出登录");
        fileMenu.getItems().addAll(exportItem, importItem, new SeparatorMenuItem(), logoutItem);
        
        // 用户管理菜单（仅管理员可见）
        Menu userMenu = new Menu("用户管理");
        MenuItem userListItem = new MenuItem("用户列表");
        MenuItem addUserItem = new MenuItem("添加用户");
        userMenu.getItems().addAll(userListItem, addUserItem);
        userMenu.setVisible("admin".equals(DatabaseManager.getUserRole(currentUsername)));
        
        menuBar.getMenus().addAll(fileMenu, userMenu);
        
        // 事件处理
        logoutItem.setOnAction(e -> logout());
        userListItem.setOnAction(e -> showUserManageDialog());
        addUserItem.setOnAction(e -> showAddUserDialog());
        
        return menuBar;
    }

    private VBox createLeftPanel() {
        VBox leftPanel = new VBox(10);
        leftPanel.setPadding(new Insets(10));
        leftPanel.getStyleClass().add("left-panel");
        leftPanel.setPrefWidth(200);

        // 添加用户信息区域
        VBox userInfoBox = createUserInfoBox();
        
        // 添加分隔线
        Separator separator = new Separator(Orientation.HORIZONTAL);
        separator.setPadding(new Insets(5, 0, 5, 0));

        Button overviewBtn = new Button("总览");
        Button incomeBtn = new Button("收入管理");
        Button expenseBtn = new Button("支出管理");
        Button assetBtn = new Button("资产管理");
        Button familyAssetBtn = new Button("家庭资产");  // 新增按钮
        Button reportBtn = new Button("统计报表");
        Button settingsBtn = new Button("设置");

        leftPanel.getChildren().addAll(
            userInfoBox,
            separator,
            overviewBtn,
            incomeBtn,
            expenseBtn,
            assetBtn,
            familyAssetBtn,  // 添加到导航栏
            reportBtn,
            settingsBtn
        );

        // 设置按钮事件
        overviewBtn.setOnAction(e -> showOverview());
        incomeBtn.setOnAction(e -> showIncomeManagement());
        expenseBtn.setOnAction(e -> showExpenseManagement());
        assetBtn.setOnAction(e -> showAssetView());
        familyAssetBtn.setOnAction(e -> showFamilyAssetView());  // 添加事件处理
        reportBtn.setOnAction(e -> showReportView());
        settingsBtn.setOnAction(e -> showSettingsView());

        return leftPanel;
    }

    private VBox createUserInfoBox() {
        VBox userInfoBox = new VBox(5);
        userInfoBox.setAlignment(Pos.CENTER);
        userInfoBox.setPadding(new Insets(10));
        userInfoBox.getStyleClass().add("user-info-box");

        // 创建头像显示
        ImageView avatarView = new ImageView();
        avatarView.setFitWidth(64);
        avatarView.setFitHeight(64);
        avatarView.getStyleClass().add("avatar");

        // 加载用户头像
        String avatarPath = DatabaseManager.getUserAvatarPath(currentUsername);
        try {
            Image avatar;
            if (avatarPath != null && !avatarPath.isEmpty()) {
                File avatarFile = new File(avatarPath);
                if (avatarFile.exists()) {
                    avatar = new Image(avatarFile.toURI().toString());
                } else {
                    avatar = new Image(getClass().getResourceAsStream("/images/default-avatar.png"));
                }
            } else {
                avatar = new Image(getClass().getResourceAsStream("/images/default-avatar.png"));
            }
            avatarView.setImage(avatar);
        } catch (Exception e) {
            e.printStackTrace();
            Circle defaultAvatar = new Circle(32);
            defaultAvatar.setFill(Color.LIGHTGRAY);
            avatarView.setClip(defaultAvatar);
        }

        // 获取并显示用户信息
        String name = DatabaseManager.getUserName(currentUsername);
        Label nameLabel = new Label(name);
        nameLabel.getStyleClass().add("name-label");

        String role = DatabaseManager.getUserRole(currentUsername);
        Label roleLabel = new Label("admin".equals(role) ? "管理员" : "普通用户");
        roleLabel.getStyleClass().add("role-label");

        userInfoBox.getChildren().addAll(avatarView, nameLabel, roleLabel);
        return userInfoBox;
    }

    private void showOverview() {
        content = new VBox(20);
        content.setPadding(new Insets(20));
        content.getStyleClass().add("overview-panel");
        
        // 1. 添加标题
        Label titleLabel = new Label("账务总览");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 2. 创建统计卡片区域
        HBox statsCards = new HBox(20);
        statsCards.setAlignment(Pos.CENTER);

        // 创建统计卡片（先用0值初始化）
        VBox incomeCard = createStatsCard("本月收入", "¥0.00", "income-card");
        VBox expenseCard = createStatsCard("本月支出", "¥0.00", "expense-card");
        VBox balanceCard = createStatsCard("本月结余", "¥0.00", "balance-card");
        
        statsCards.getChildren().addAll(incomeCard, expenseCard, balanceCard);
        
        // 3. 创建月份选择和交易记录区域
        VBox transactionsBox = new VBox(10);
        HBox filterBox = new HBox(10);
        filterBox.setAlignment(Pos.CENTER_LEFT);
        
        // 添加月份选择器
        Label monthLabel = new Label("选择月份:");
        DatePicker monthPicker = new DatePicker(LocalDate.now());
        monthPicker.setShowWeekNumbers(false);
        
        // 自定义月份选择器的显示格式
        StringConverter<LocalDate> converter = new StringConverter<LocalDate>() {
            private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
            
            @Override
            public String toString(LocalDate date) {
                if (date != null) {
                    return dateFormatter.format(date);
                } else {
                    return "";
                }
            }

            @Override
            public LocalDate fromString(String string) {
                if (string != null && !string.isEmpty()) {
                    return LocalDate.parse(string + "-01");
                } else {
                    return null;
                }
            }
        };
        monthPicker.setConverter(converter);
        
        // 设置月份选择器的日期单元格工厂
        monthPicker.setDayCellFactory(picker -> new DateCell() {
            @Override
            public void updateItem(LocalDate date, boolean empty) {
                super.updateItem(date, empty);
                // 禁用日期选择，但允许月份选择
                if (date != null && !empty) {
                    if (date.getDayOfMonth() != 1) {
                        setDisable(true);
                        setStyle("-fx-background-color: #fafafa;");
                    }
                }
            }
        });
        
        // 监听日期变化，自动设置为每月1号
        monthPicker.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                // 如果选择的不是1号，自动调整为当月1号
                if (newVal.getDayOfMonth() != 1) {
                    monthPicker.setValue(newVal.withDayOfMonth(1));
                }
            }
        });
        
        // 添加刷新按钮
        Button refreshBtn = new Button("查看");
        refreshBtn.setOnAction(e -> {
            if (monthPicker.getValue() != null) {
                refreshTransactionsByMonth(monthPicker.getValue());
            }
        });
        
        // 添加导出按钮
        Button exportBtn = new Button("导出");
        exportBtn.getStyleClass().add("secondary-button");
        exportBtn.setOnAction(e -> exportTransactions(monthPicker.getValue()));
        
        // 设置月份选择器的样式
        monthPicker.setStyle("-fx-pref-width: 120px;");
        
        filterBox.getChildren().addAll(monthLabel, monthPicker, refreshBtn, new Separator(Orientation.VERTICAL), exportBtn);
        
        Label transactionLabel = new Label("交易记录");
        transactionLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        transactionsBox.getChildren().addAll(transactionLabel, filterBox, transactionTable);
        
        // 4. 将所有内容添加到主容器
        content.getChildren().addAll(titleLabel, statsCards, transactionsBox);
        root.setCenter(content);
        
        // 5. 最后刷新数据
        refreshTransactionsByMonth(LocalDate.now());
    }

    // 添加导出功能
    private void exportTransactions(LocalDate date) {
        if (transactions.isEmpty()) {
            showError("导出失败", "没有可导出的数据");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择保存位置");
        fileChooser.setInitialFileName(String.format("交易记录_%s.xlsx", 
            date.format(DateTimeFormatter.ofPattern("yyyy年MM月"))));
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
        );

        File file = fileChooser.showSaveDialog(root.getScene().getWindow());
        if (file != null) {
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                XSSFSheet sheet = workbook.createSheet("交易记录");

                // 创建标题行样式
                XSSFCellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                headerStyle.setAlignment(HorizontalAlignment.CENTER);
                
                XSSFFont headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建标题行
                Row headerRow = sheet.createRow(0);
                String[] headers = {"日期", "类型", "类别", "账户", "金额", "描述"};
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(headers[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.setColumnWidth(i, 15 * 256); // 设置列宽
                }

                // 创建金额样式
                XSSFCellStyle amountStyle = workbook.createCellStyle();
                amountStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));

                // 添加数据行
                int rowNum = 1;
                for (Transaction transaction : transactions) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(transaction.getDate().toString());
                    row.createCell(1).setCellValue(transaction.getType());
                    row.createCell(2).setCellValue(transaction.getCategory());
                    row.createCell(3).setCellValue(transaction.getAssetName());
                    
                    Cell amountCell = row.createCell(4);
                    amountCell.setCellValue(transaction.getAmount());
                    amountCell.setCellStyle(amountStyle);
                    
                    row.createCell(5).setCellValue(transaction.getDescription());
                }

                // 添加统计行
                Row totalRow = sheet.createRow(rowNum + 1);
                totalRow.createCell(0).setCellValue("统计");
                
                // 计算收入总额
                double totalIncome = transactions.stream()
                    .filter(t -> "收入".equals(t.getType()))
                    .mapToDouble(Transaction::getAmount)
                    .sum();
                
                // 计算支出总额
                double totalExpense = transactions.stream()
                    .filter(t -> "支出".equals(t.getType()))
                    .mapToDouble(Transaction::getAmount)
                    .sum();

                Cell incomeTotalCell = totalRow.createCell(1);
                incomeTotalCell.setCellValue("收入总额：" + String.format("%.2f", totalIncome));
                
                Cell expenseTotalCell = totalRow.createCell(2);
                expenseTotalCell.setCellValue("支出总额：" + String.format("%.2f", totalExpense));
                
                Cell balanceTotalCell = totalRow.createCell(3);
                balanceTotalCell.setCellValue("结余：" + String.format("%.2f", totalIncome - totalExpense));

                // 保存文件
                try (FileOutputStream outputStream = new FileOutputStream(file)) {
                    workbook.write(outputStream);
                }

                showInfo("导出成功", "交易记录已成功导出到：" + file.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
                showError("导出失败", "导出过程中发生错误：" + e.getMessage());
            }
        }
    }

    private void refreshTransactionsByMonth(LocalDate date) {
        try (Connection conn = DatabaseManager.getConnection()) {
            // 1. 先更新交易记录 - 移除用户ID限制，显示所有用户的记录
            String sql = """
                SELECT t.*, u.name as user_name 
                FROM transactions t
                LEFT JOIN users u ON t.user_id = u.id
                WHERE strftime('%Y-%m', date) = ?
                ORDER BY t.date DESC
                """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            String yearMonth = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            pstmt.setString(1, yearMonth);
            
            ResultSet rs = pstmt.executeQuery();
            
            transactions.clear();
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transaction.setUserId(rs.getInt("user_id"));
                transaction.setAssetName(rs.getString("user_name") != null ? 
                    rs.getString("user_name") : "未知用户");  // 添加空值处理
                transactions.add(transaction);
            }
            
            // 2. 更新统计数据 - 计算所有用户的收支总额
            double monthlyIncome = calculateTotalMonthlyIncomeByDate(date);
            double monthlyExpense = calculateTotalMonthlyExpenseByDate(date);
            double balance = monthlyIncome - monthlyExpense;
            
            // 3. 更新统计卡片
            Platform.runLater(() -> {
                if (content != null && content.getChildren().size() > 1) {
                    HBox statsCards = (HBox) content.getChildren().get(1);
                    for (Node node : statsCards.getChildren()) {
                        VBox card = (VBox) node;
                        Label valueLabel = (Label) card.getChildren().get(1);
                        if (card.getStyleClass().contains("income-card")) {
                            valueLabel.setText(String.format("¥%.2f", monthlyIncome));
                        } else if (card.getStyleClass().contains("expense-card")) {
                            valueLabel.setText(String.format("¥%.2f", monthlyExpense));
                        } else if (card.getStyleClass().contains("balance-card")) {
                            valueLabel.setText(String.format("¥%.2f", balance));
                        }
                    }
                }
            });
            
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载失败", "加载交易记录时发生错误");
        }
    }

    // 计算所有用户的月收入总额
    private double calculateTotalMonthlyIncomeByDate(LocalDate date) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT SUM(amount) FROM transactions 
                WHERE type = '收入' 
                AND strftime('%Y-%m', date) = ?
                """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            String yearMonth = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            pstmt.setString(1, yearMonth);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("计算失败", "计算收入时发生错误");
        }
        return 0.0;
    }

    // 计算所有用户的月支出总额
    private double calculateTotalMonthlyExpenseByDate(LocalDate date) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT SUM(amount) FROM transactions 
                WHERE type = '支出' 
                AND strftime('%Y-%m', date) = ?
                """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            String yearMonth = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            pstmt.setString(1, yearMonth);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("计算失败", "计算支出时发生错误");
        }
        return 0.0;
    }

    // 创建统计卡片的辅助方法
    private VBox createStatsCard(String title, String value, String styleClass) {
        VBox card = new VBox(10);
        card.setPadding(new Insets(20));
        card.setMinWidth(200);
        card.setMinHeight(120);
        card.getStyleClass().addAll("stats-card", styleClass);
        card.setAlignment(Pos.CENTER);

        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-size: 16px;");
        
        Label valueLabel = new Label(value);
        valueLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");

        card.getChildren().addAll(titleLabel, valueLabel);
        return card;
    }

    // 计算本月收入
    private double calculateMonthlyIncome() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT SUM(amount) FROM transactions 
                WHERE type = '收入' 
                AND strftime('%Y-%m', date) = strftime('%Y-%m', 'now')
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("计算失败", "计算本月收入时发生错误");
        }
        return 0.0;
    }

    // 计算本月支出
    private double calculateMonthlyExpense() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT SUM(amount) FROM transactions 
                WHERE type = '支出' 
                AND strftime('%Y-%m', date) = strftime('%Y-%m', 'now')
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getDouble(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("计算失败", "计算本月支出时发生错误");
        }
        return 0.0;
    }

    // 刷新最近交易记录
    private void refreshRecentTransactions() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT t.*, u.name as user_name 
                FROM transactions t
                LEFT JOIN users u ON t.user_id = u.id
                WHERE t.user_id = ?
                ORDER BY t.date DESC LIMIT 10
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, DatabaseManager.getUserId(currentUsername));
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transaction.setUserId(rs.getInt("user_id"));
                transaction.setAssetName(rs.getString("user_name"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载失败", "加载最近交易记录时发生错误");
        }
    }

    private void showIncomeManagement() {
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 工具栏
        HBox toolbar = new HBox(10);
        Button addBtn = new Button("新增收入");
        addBtn.setOnAction(e -> showAddTransactionDialog("收入"));
        
        toolbar.getChildren().addAll(addBtn);
        
        // 初始化表格
        TableView<Transaction> incomeTable = new TableView<>();
        incomeTransactions = FXCollections.observableArrayList();
        
        // 设置表格列
        setupTransactionTable(incomeTable, incomeTransactions);
        
        content.getChildren().addAll(toolbar, incomeTable);
        root.setCenter(content);
        
        // 刷新表格，只显示收入记录
        refreshTransactions(incomeTransactions, "收入");
    }

    private void showExpenseManagement() {
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 工具栏
        HBox toolbar = new HBox(10);
        Button addBtn = new Button("新增支出");
        addBtn.setOnAction(e -> showAddTransactionDialog("支出"));
        
        toolbar.getChildren().addAll(addBtn);
        
        // 初始化表格
        TableView<Transaction> expenseTable = new TableView<>();
        expenseTransactions = FXCollections.observableArrayList();
        
        // 设置表格列
        setupTransactionTable(expenseTable, expenseTransactions);
        
        content.getChildren().addAll(toolbar, expenseTable);
        root.setCenter(content);
        
        // 刷新表格，只显示支出记录
        refreshTransactions(expenseTransactions, "支出");
    }

    // 辅助方法：刷新交易记录
    private void refreshTransactions(ObservableList<Transaction> transactions, String type) {
        DatabaseManager.refreshTransactions(
            transactions, 
            DatabaseManager.getUserId(currentUsername),
            type
        );
    }

    private void showIncomeView() {
        VBox centerContent = new VBox(15);
        centerContent.setPadding(new Insets(20));
        centerContent.getStyleClass().add("overview-panel");

        // 1. 添加标题
        Label titleLabel = new Label("收入管理");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");

        // 2. 创建工具栏
        HBox toolbar = new HBox(15);
        toolbar.setAlignment(Pos.CENTER_LEFT);
        
        Button addBtn = new Button("新增收入");
        addBtn.getStyleClass().add("primary-button");
        addBtn.setOnAction(e -> showAddTransactionDialog("收入"));
        
        Button deleteBtn = new Button("删除");
        deleteBtn.getStyleClass().add("danger-button");
        deleteBtn.setDisable(true);
        deleteBtn.setOnAction(e -> deleteSelectedTransaction());

        ComboBox<String> categoryFilter = new ComboBox<>();
        categoryFilter.getItems().addAll(DatabaseManager.getCategories("收入"));
        categoryFilter.getItems().add(0, "全部类别");
        categoryFilter.setValue("全部类别");
        categoryFilter.setMinWidth(120);
        categoryFilter.setOnAction(e -> filterIncomeByCategory(categoryFilter.getValue()));

        toolbar.getChildren().addAll(addBtn, deleteBtn, new Separator(Orientation.VERTICAL), categoryFilter);

        // 3. 设置表格选择监听
        transactionTable.getSelectionModel().selectedItemProperty().addListener(
            (obs, oldSelection, newSelection) -> deleteBtn.setDisable(newSelection == null)
        );

        centerContent.getChildren().addAll(titleLabel, toolbar, transactionTable);
        VBox.setVgrow(transactionTable, Priority.ALWAYS);
        
        root.setCenter(centerContent);
        refreshIncomeTransactions();
    }

    private void showExpenseView() {
        VBox centerContent = new VBox(15);
        centerContent.setPadding(new Insets(20));
        centerContent.getStyleClass().add("overview-panel");

        // 1. 添加标题
        Label titleLabel = new Label("支出管理");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");

        // 2. 创建工具栏
        HBox toolbar = new HBox(15);
        toolbar.setAlignment(Pos.CENTER_LEFT);
        
        Button addBtn = new Button("新增支出");
        addBtn.getStyleClass().add("primary-button");
        addBtn.setOnAction(e -> showAddTransactionDialog("支出"));
        
        Button deleteBtn = new Button("删除");
        deleteBtn.getStyleClass().add("danger-button");
        deleteBtn.setDisable(true);
        deleteBtn.setOnAction(e -> deleteSelectedTransaction());

        ComboBox<String> categoryFilter = new ComboBox<>();
        categoryFilter.getItems().addAll(DatabaseManager.getCategories("支出"));
        categoryFilter.getItems().add(0, "全部类别");
        categoryFilter.setValue("全部类别");
        categoryFilter.setMinWidth(120);
        categoryFilter.setOnAction(e -> filterExpenseByCategory(categoryFilter.getValue()));

        toolbar.getChildren().addAll(addBtn, deleteBtn, new Separator(Orientation.VERTICAL), categoryFilter);

        // 3. 设置表格选择监听
        transactionTable.getSelectionModel().selectedItemProperty().addListener(
            (obs, oldSelection, newSelection) -> deleteBtn.setDisable(newSelection == null)
        );

        centerContent.getChildren().addAll(titleLabel, toolbar, transactionTable);
        VBox.setVgrow(transactionTable, Priority.ALWAYS);
        
        root.setCenter(centerContent);
        refreshExpenseTransactions();
    }

    // 添加新的辅助方法
    private void showAddTransactionDialog(String type) {
        Dialog<Transaction> dialog = new Dialog<>();
        dialog.setTitle("添加" + type);
        dialog.setHeaderText(null);
        
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));
        
        DatePicker datePicker = new DatePicker(LocalDate.now());
        
        // 类别下拉框
        ComboBox<String> categoryCombo = new ComboBox<>();
        if ("收入".equals(type)) {
            categoryCombo.getItems().addAll(
                "工资", "奖金", "投资收益", "兼职收入", "其他收入"
            );
        } else {
            categoryCombo.getItems().addAll(
                "餐饮", "购物", "交通", "住房", "娱乐",
                "医疗", "教育", "通讯", "其他支出"
            );
        }
        categoryCombo.setPromptText("请选择类别");
        
        TextField amountField = new TextField();
        TextArea descArea = new TextArea();
        descArea.setPrefRowCount(3);
        
        // 获取当前用户名
        String userName = DatabaseManager.getUserName(currentUsername);
        Label accountLabel = new Label(userName);
        
        grid.add(new Label("日期:"), 0, 0);
        grid.add(datePicker, 1, 0);
        grid.add(new Label("类别:"), 0, 1);
        grid.add(categoryCombo, 1, 1);
        grid.add(new Label("账户:"), 0, 2);
        grid.add(accountLabel, 1, 2);
        grid.add(new Label("金额:"), 0, 3);
        grid.add(amountField, 1, 3);
        grid.add(new Label("描述:"), 0, 4);
        grid.add(descArea, 1, 4);
        
        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        
        // 添加验证
        Node okButton = dialog.getDialogPane().lookupButton(ButtonType.OK);
        okButton.setDisable(true);
        
        // 验证输入
        BooleanBinding isInvalid = Bindings.createBooleanBinding(() ->
            datePicker.getValue() == null ||
            categoryCombo.getValue() == null ||
            amountField.getText().trim().isEmpty() ||
            !isValidNumber(amountField.getText()),
            datePicker.valueProperty(),
            categoryCombo.valueProperty(),
            amountField.textProperty()
        );
        
        okButton.disableProperty().bind(isInvalid);
        
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == ButtonType.OK) {
                try {
                    Transaction transaction = new Transaction();
                    transaction.setDate(datePicker.getValue());
                    transaction.setType(type);
                    transaction.setCategory(categoryCombo.getValue());
                    transaction.setAmount(Double.parseDouble(amountField.getText().trim()));
                    transaction.setDescription(descArea.getText());
                    transaction.setUserId(DatabaseManager.getUserId(currentUsername));
                    transaction.setAssetName(userName);
                    
                    return transaction;
                } catch (Exception e) {
                    showError("输入错误", "请检查输入的数据格式是否正确。");
                    return null;
                }
            }
            return null;
        });
        
        dialog.showAndWait().ifPresent(transaction -> {
            if (DatabaseManager.addTransaction(transaction)) {
                // 根据类型刷新对应的表格
                if ("收入".equals(type)) {
                    refreshTransactions(incomeTransactions, "收入");
                } else {
                    refreshTransactions(expenseTransactions, "支出");
                }
            } else {
                showError("错误", "添加交易记录失败");
            }
        });
    }

    private void showCategoryDialog(String type) {
        Dialog<Void> categoryDialog = new Dialog<>();
        categoryDialog.setTitle(type + "类别管理");
        categoryDialog.setHeaderText("管理" + type + "类别");
        
        VBox content = new VBox(10);
        content.setPadding(new Insets(20));
        
        ListView<String> categoryList = new ListView<>();
        categoryList.setItems(FXCollections.observableArrayList(DatabaseManager.getCategories(type)));
        
        HBox buttonBox = new HBox(10);
        Button addBtn = new Button("添加");
        Button editBtn = new Button("编辑");
        Button deleteBtn = new Button("删除");
        buttonBox.getChildren().addAll(addBtn, editBtn, deleteBtn);
        
        // 添加类别
        addBtn.setOnAction(event -> {
            TextInputDialog addDialog = new TextInputDialog();
            addDialog.setTitle("添加类别");
            addDialog.setHeaderText(null);
            addDialog.setContentText("请输入新的类别名称：");

            addDialog.showAndWait().ifPresent(name -> {
                if (!name.trim().isEmpty()) {
                    if (DatabaseManager.addCategory(type, name.trim())) {
                        categoryList.getItems().clear();
                        categoryList.getItems().addAll(DatabaseManager.getCategories(type));
                    }
                }
            });
        });

        // 编辑类别
        editBtn.setOnAction(event -> {
            String selected = categoryList.getSelectionModel().getSelectedItem();
            if (selected != null) {
                TextInputDialog editDialog = new TextInputDialog(selected);
                editDialog.setTitle("编辑类别");
                editDialog.setHeaderText(null);
                editDialog.setContentText("请输入新的类别名称：");

                editDialog.showAndWait().ifPresent(name -> {
                    if (!name.trim().isEmpty()) {
                        if (DatabaseManager.updateCategory(type, selected, name.trim())) {
                            categoryList.getItems().clear();
                            categoryList.getItems().addAll(DatabaseManager.getCategories(type));
                        }
                    }
                });
            }
        });

        // 删除类别
        deleteBtn.setOnAction(event -> {
            String selected = categoryList.getSelectionModel().getSelectedItem();
            if (selected != null) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("确认删除");
                alert.setHeaderText(null);
                alert.setContentText("确定要删除这个类别吗？");

                alert.showAndWait().ifPresent(response -> {
                    if (response == ButtonType.OK) {
                        if (DatabaseManager.deleteCategory(type, selected)) {
                            categoryList.getItems().clear();
                            categoryList.getItems().addAll(DatabaseManager.getCategories(type));
                        }
                    }
                });
            }
        });

        content.getChildren().addAll(categoryList, buttonBox);
        categoryDialog.getDialogPane().setContent(content);
        categoryDialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
        
        categoryDialog.showAndWait();
    }

    private void refreshIncomeTransactions() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = "SELECT * FROM transactions WHERE type = '收入' ORDER BY date DESC";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载失败", "加载收入记录时发生错误");
        }
    }

    private void refreshExpenseTransactions() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = "SELECT * FROM transactions WHERE type = '支出' ORDER BY date DESC";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载失败", "加载支出记录时发生错误");
        }
    }

    private void filterIncomeByCategory(String category) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = "全部类别".equals(category) 
                ? "SELECT * FROM transactions WHERE type = '收入' ORDER BY date DESC"
                : "SELECT * FROM transactions WHERE type = '收入' AND category = ? ORDER BY date DESC";
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            if (!"全部类别".equals(category)) {
                pstmt.setString(1, category);
            }
            
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("筛选失败", "按类别筛选收入记录时发生错误");
        }
    }

    private void filterExpenseByCategory(String category) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = "全部类别".equals(category) 
                ? "SELECT * FROM transactions WHERE type = '支出' ORDER BY date DESC"
                : "SELECT * FROM transactions WHERE type = '支出' AND category = ? ORDER BY date DESC";
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            if (!"全部类别".equals(category)) {
                pstmt.setString(1, category);
            }
            
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("筛选失败", "按类别筛选支出记录时发生错误");
        }
    }

    private void showSettingsView() {
        VBox settingsView = new VBox(20);
        settingsView.setPadding(new Insets(20));
        settingsView.setStyle("-fx-background-color: white");

        Label titleLabel = new Label("系统设置");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 主题设置
        VBox themeBox = new VBox(10);
        Label themeLabel = new Label("主题设置");
        themeLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        ComboBox<String> themeCombo = new ComboBox<>();
        themeCombo.getItems().addAll("浅色主题", "深色主题");
        themeCombo.setValue(ConfigManager.getTheme().equals("dark") ? "深色主题" : "浅色主题");
        themeCombo.setOnAction(e -> {
            String theme = themeCombo.getValue().equals("深色主题") ? "dark" : "light";
            ConfigManager.setTheme(theme);
            applyTheme(theme);
        });
        themeBox.getChildren().addAll(themeLabel, themeCombo);
        
        // 语言设置
        VBox languageBox = new VBox(10);
        Label languageLabel = new Label("语言设置");
        languageLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        ComboBox<String> languageCombo = new ComboBox<>();
        languageCombo.getItems().addAll("简体中文", "English");
        languageCombo.setValue(ConfigManager.getLanguage().equals("en") ? "English" : "简体中文");
        languageCombo.setOnAction(e -> {
            String language = languageCombo.getValue().equals("English") ? "en" : "zh_CN";
            ConfigManager.setLanguage(language);
            showInfo("设置已保存", "语言设置将在重启应用后生效");
        });
        languageBox.getChildren().addAll(languageLabel, languageCombo);

        // 数据备份
        VBox backupBox = new VBox(10);
        Label backupLabel = new Label("数据备份");
        backupLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        HBox backupButtonBox = new HBox(10);
        Button backupBtn = new Button("备份数据");
        Button restoreBtn = new Button("恢复数据");
        
        backupBtn.setOnAction(e -> backupDatabase());
        restoreBtn.setOnAction(e -> restoreDatabase());
        
        backupButtonBox.getChildren().addAll(backupBtn, restoreBtn);
        backupBox.getChildren().addAll(backupLabel, backupButtonBox);

        // 用户管理（仅管理员可见）
        if ("admin".equals(DatabaseManager.getUserRole(currentUsername))) {
            VBox userManageBox = new VBox(10);
            Label userLabel = new Label("用户管理");
            userLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
            
            TableView<User> userTable = new TableView<>();
            
            TableColumn<User, String> usernameCol = new TableColumn<>("用户名");
            usernameCol.setCellValueFactory(new PropertyValueFactory<>("username"));
            
            TableColumn<User, String> nameCol = new TableColumn<>("姓名");
            nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
            
            TableColumn<User, String> roleCol = new TableColumn<>("角色");
            roleCol.setCellValueFactory(new PropertyValueFactory<>("role"));
            
            TableColumn<User, String> createTimeCol = new TableColumn<>("创建时间");
            createTimeCol.setCellValueFactory(new PropertyValueFactory<>("createTime"));
            
            userTable.getColumns().addAll(usernameCol, nameCol, roleCol, createTimeCol);
            userTable.setItems(FXCollections.observableArrayList(DatabaseManager.getAllUsers()));
            
            // 添加删除按钮
            Button deleteBtn = new Button("删除用户");
            deleteBtn.getStyleClass().add("danger-button");
            deleteBtn.setDisable(true);
            
            userTable.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> 
                deleteBtn.setDisable(newSelection == null || "admin".equals(newSelection.getUsername()))
            );
            
            deleteBtn.setOnAction(e -> {
                User selectedUser = userTable.getSelectionModel().getSelectedItem();
                if (selectedUser != null) {
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setTitle("确认删除");
                    alert.setHeaderText(null);
                    alert.setContentText("确定要删除用户 \"" + selectedUser.getName() + "\" 吗？");
                    
                    alert.showAndWait().ifPresent(response -> {
                        if (response == ButtonType.OK) {
                            if (DatabaseManager.deleteUser(selectedUser.getId())) {
                                userTable.getItems().setAll(DatabaseManager.getAllUsers());
                            }
                        }
                    });
                }
            });
            
            userManageBox.getChildren().addAll(userLabel, userTable, deleteBtn);
            settingsView.getChildren().add(new Separator());
            settingsView.getChildren().add(userManageBox);
        }
        
        settingsView.getChildren().addAll(
            titleLabel,
            themeBox,
            new Separator(),
            languageBox,
            new Separator(),
            backupBox
        );
        
        root.setCenter(settingsView);
    }

    private void showReportView() {
        ReportView reportView = new ReportView();
        root.setCenter(reportView.getView());
    }

    public Parent getView() {
        return root;
    }

    private void deleteSelectedTransaction() {
        Transaction selected = transactionTable.getSelectionModel().getSelectedItem();
        if (selected != null) {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认删除");
            alert.setHeaderText(null);
            alert.setContentText("确定要删除这条记录吗？");

            alert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    // 从数据库删除
                    deleteTransaction(selected);
                    // 刷新表格
                    refreshTransactionTable();
                }
            });
        }
    }

    private void filterTransactions(String filter) {
        // 根据选择的过滤条件刷新表格
        refreshTransactionTable(filter);
    }

    // 辅助方法
    private void showError(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    private void saveTransaction(Transaction transaction) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                INSERT INTO transactions (date, type, category, amount, description)
                VALUES (?, ?, ?, ?, ?)
                """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            
            // 添加日志输出，帮助调试
            System.out.println("Saving transaction:");
            System.out.println("Date: " + transaction.getDate());
            System.out.println("Type: " + transaction.getType());
            System.out.println("Category: " + transaction.getCategory());
            System.out.println("Amount: " + transaction.getAmount());
            System.out.println("Description: " + transaction.getDescription());
            
            // 设置参数
            pstmt.setString(1, transaction.getDate().toString());
            pstmt.setString(2, transaction.getType());
            pstmt.setString(3, transaction.getCategory());
            pstmt.setDouble(4, transaction.getAmount());
            pstmt.setString(5, transaction.getDescription());
            
            int result = pstmt.executeUpdate();
            if (result > 0) {
                showSuccess("保存成功", "记录已成功保存。");
            } else {
                showError("保存失败", "数据未能成功保存到数据库。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("保存失败", "保存记录时发生错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            showError("保存失败", "发生未知错误：" + e.getMessage());
        }
    }

    private void deleteTransaction(Transaction transaction) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = "DELETE FROM transactions WHERE id = ?";
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, transaction.getId());
            
            pstmt.executeUpdate();
            showSuccess("删除成功", "记录已成功删除。");
        } catch (SQLException e) {
            e.printStackTrace();
            showError("删除失败", "删除记录时发生错误：" + e.getMessage());
        }
    }

    private void refreshTransactionTable() {
        refreshTransactionTable("全部");
    }

    private void refreshTransactionTable(String filter) {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT * FROM transactions
                WHERE type LIKE ?
                ORDER BY date DESC
                """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            if ("全部".equals(filter)) {
                pstmt.setString(1, "%");
            } else {
                pstmt.setString(1, filter);
            }
            
            ResultSet rs = pstmt.executeQuery();
            transactions.clear();
            
            while (rs.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(rs.getInt("id"));
                transaction.setDate(LocalDate.parse(rs.getString("date")));
                transaction.setType(rs.getString("type"));
                transaction.setCategory(rs.getString("category"));
                transaction.setAmount(rs.getDouble("amount"));
                transaction.setDescription(rs.getString("description"));
                transactions.add(transaction);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载失败", "加载数据时发生错误：" + e.getMessage());
        }
    }

    private void showSuccess(String title, String content) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle(title);
            alert.setHeaderText(null);
            alert.setContentText(content);
            alert.showAndWait();
        });
    }

    private void showInfo(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    private void applyTheme(String theme) {
        Scene scene = root.getScene();
        scene.getStylesheets().clear();
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        
        if ("dark".equals(theme)) {
            scene.getStylesheets().add(getClass().getResource("/css/themes/dark-theme.css").toExternalForm());
        }
    }

    private void backupDatabase() {
        // 实现备份数据库的逻辑
        showInfo("备份数据", "数据备份功能尚未实现。");
    }

    private void restoreDatabase() {
        // 实现恢复数据库的逻辑
        showInfo("恢复数据", "数据恢复功能尚未实现。");
    }

    private void showAddTransactionTypeDialog() {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("选择记录类型");
        dialog.setHeaderText("请选择要添加的记录类型");

        ButtonType incomeButtonType = new ButtonType("收入", ButtonBar.ButtonData.LEFT);
        ButtonType expenseButtonType = new ButtonType("支出", ButtonBar.ButtonData.RIGHT);
        
        dialog.getDialogPane().getButtonTypes().addAll(incomeButtonType, expenseButtonType, ButtonType.CANCEL);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == incomeButtonType) {
                return "收入";
            } else if (dialogButton == expenseButtonType) {
                return "支出";
            }
            return null;
        });

        dialog.showAndWait().ifPresent(type -> showAddTransactionDialog(type));
    }

    // 退出登录方法
    private void logout() {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认退出");
        alert.setHeaderText(null);
        alert.setContentText("确定要退出登录吗？");
        
        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                // 获取当前窗口
                Stage stage = (Stage) root.getScene().getWindow();
                
                // 创建新的登录场景
                LoginView loginView = new LoginView();
                Scene loginScene = new Scene(loginView.getView(), 400, 300);
                loginScene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
                
                // 设置登录成功的回调
                loginView.setOnLogin(() -> {
                    if (DatabaseManager.validateUser(loginView.getUsername(), loginView.getPassword())) {
                        // 创建新的主场景
                        MainView mainView = new MainView(loginView.getUsername());
                        Scene mainScene = new Scene(mainView.getView(), 1000, 700);
                        mainScene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
                        
                        // 显示主场景
                        stage.setScene(mainScene);
                        stage.setTitle("家庭记账系统");
                        stage.setMaximized(true);
                    }
                });
                
                // 清除用户角色缓存
                DatabaseManager.clearUserRoleCache();
                
                // 显示登录场景
                stage.setScene(loginScene);
                stage.setTitle("登录 - 家庭记账系统");
                stage.setMaximized(false);
                stage.setWidth(400);
                stage.setHeight(300);
                stage.centerOnScreen();
            }
        });
    }

    // 用户管理对话框
    private void showUserManageDialog() {
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("用户管理");
        dialog.setHeaderText("管理系统用户");
        
        VBox content = new VBox(10);
        content.setPadding(new Insets(20));
        
        TableView<User> userTable = new TableView<>();
        
        TableColumn<User, String> usernameCol = new TableColumn<>("用户名");
        TableColumn<User, String> nameCol = new TableColumn<>("姓名");
        TableColumn<User, String> roleCol = new TableColumn<>("角色");
        TableColumn<User, String> createTimeCol = new TableColumn<>("创建时间");
        
        usernameCol.setCellValueFactory(new PropertyValueFactory<>("username"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        roleCol.setCellValueFactory(new PropertyValueFactory<>("role"));
        createTimeCol.setCellValueFactory(new PropertyValueFactory<>("createTime"));
        
        // 添加角色编辑功能
        roleCol.setCellFactory(column -> new TableCell<User, String>() {
            private final ComboBox<String> comboBox = new ComboBox<>();
            
            {
                comboBox.getItems().addAll("member", "admin");
                comboBox.setOnAction(e -> {
                    User user = getTableView().getItems().get(getIndex());
                    String newRole = comboBox.getValue();
                    if (!newRole.equals(user.getRole())) {
                        DatabaseManager.updateUserRole(user.getId(), newRole);
                        user.setRole(newRole);
                    }
                });
            }
            
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    User user = getTableView().getItems().get(getIndex());
                    comboBox.setValue(user.getRole());
                    setGraphic(comboBox);
                    // 禁止修改admin用户的角色
                    comboBox.setDisable("admin".equals(user.getUsername()));
                }
            }
        });
        
        userTable.getColumns().addAll(usernameCol, nameCol, roleCol, createTimeCol);
        userTable.setItems(FXCollections.observableArrayList(DatabaseManager.getAllUsers()));
        
        // 添加删除按钮
        Button deleteBtn = new Button("删除用户");
        deleteBtn.getStyleClass().add("danger-button");
        deleteBtn.setDisable(true);
        
        userTable.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> 
            deleteBtn.setDisable(newSelection == null || "admin".equals(newSelection.getUsername()))
        );
        
        deleteBtn.setOnAction(e -> {
            User selectedUser = userTable.getSelectionModel().getSelectedItem();
            if (selectedUser != null) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("确认删除");
                alert.setHeaderText(null);
                alert.setContentText("确定要删除用户 \"" + selectedUser.getName() + "\" 吗？");
                
                alert.showAndWait().ifPresent(response -> {
                    if (response == ButtonType.OK) {
                        if (DatabaseManager.deleteUser(selectedUser.getId())) {
                            userTable.getItems().setAll(DatabaseManager.getAllUsers());
                        }
                    }
                });
            }
        });
        
        content.getChildren().addAll(userTable, deleteBtn);
        dialog.getDialogPane().setContent(content);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
        
        dialog.showAndWait();
    }

    private void showAddUserDialog() {
        // 实现添加用户的逻辑
        showInfo("添加用户", "添加用户功能尚未实现。");
    }

    private void showAssetView() {
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 工具栏
        HBox toolbar = new HBox(10);
        Button addBtn = new Button("添加资产");
        
        // 创建资产表格
        TableView<Asset> assetTable = new TableView<>();
        setupAssetTable(assetTable);
        
        addBtn.setOnAction(e -> {
            Dialog<Asset> dialog = showAssetDialog(assetTable, null);  // null 表示新增
            dialog.showAndWait().ifPresent(asset -> {
                if (DatabaseManager.addAsset(asset)) {
                    refreshAssetTable(assetTable);
                } else {
                    showError("错误", "添加资产失败");
                }
            });
        });
        
        Button editBtn = new Button("修改");
        editBtn.setOnAction(e -> {
            Asset selectedItem = assetTable.getSelectionModel().getSelectedItem();
            if (selectedItem == null) {
                showError("错误", "请选择要修改的资产");
                return;
            }
            Dialog<Asset> dialog = showAssetDialog(assetTable, selectedItem);
            dialog.showAndWait().ifPresent(updatedAsset -> {
                if (DatabaseManager.updateAsset(updatedAsset)) {
                    refreshAssetTable(assetTable);
                } else {
                    showError("错误", "更新资产失败");
                }
            });
        });
        
        Button deleteBtn = new Button("删除");
        deleteBtn.setOnAction(e -> deleteSelectedAsset(assetTable));
        
        toolbar.getChildren().addAll(addBtn, editBtn, deleteBtn);
        content.getChildren().addAll(toolbar, assetTable);
        
        // 初始加载数据
        refreshAssetTable(assetTable);
        
        root.setCenter(content);
    }

    private Dialog<Asset> showAssetDialog(TableView<Asset> table, Asset existingAsset) {
        Dialog<Asset> dialog = new Dialog<>();
        dialog.setTitle(existingAsset == null ? "添加资产" : "修改资产");
        dialog.setHeaderText("请填写资产信息");
        
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));
        
        // 创建所有控件
        ComboBox<String> typeCombo = new ComboBox<>();
        typeCombo.getItems().addAll(
            "储蓄卡", "信用卡", "现金", "支付宝", "微信钱包",
            "余额宝", "理财产品", "基金", "股票", "定期存款",
            "花呗", "京东白条", "公积金", "养老保险", "医疗保险"
        );
        
        ComboBox<String> bankCombo = new ComboBox<>();
        bankCombo.getItems().addAll(DatabaseManager.getAllBanks());
        
        TextField nameField = new TextField();
        TextField accountField = new TextField();
        TextField balanceField = new TextField();
        TextArea remarkArea = new TextArea();
        remarkArea.setPrefRowCount(3);
        
        grid.add(new Label("资产类型:"), 0, 0);
        grid.add(typeCombo, 1, 0);
        
        // 根据类型显示/隐藏相关字段
        typeCombo.setOnAction(e -> {
            String selectedType = typeCombo.getValue();
            boolean isBankCard = "储蓄卡".equals(selectedType) || "信用卡".equals(selectedType);
            
            // 更新界面显示
            bankCombo.setVisible(isBankCard);
            bankCombo.setManaged(isBankCard);
            nameField.setVisible(!isBankCard);
            nameField.setManaged(!isBankCard);
            
            // 如果不是银行卡，自动设置名称为类型名称
            if (!isBankCard && selectedType != null) {
                nameField.setText(selectedType);
            }
        });
        
        // 添加其他字段
        Label bankLabel = new Label("银行:");
        Label nameLabel = new Label("名称:");
        grid.add(bankLabel, 0, 1);
        grid.add(bankCombo, 1, 1);
        grid.add(nameLabel, 0, 1);
        grid.add(nameField, 1, 1);
        
        // 设置标签的可见性
        bankLabel.visibleProperty().bind(bankCombo.visibleProperty());
        bankLabel.managedProperty().bind(bankCombo.managedProperty());
        nameLabel.visibleProperty().bind(nameField.visibleProperty());
        nameLabel.managedProperty().bind(nameField.visibleProperty());
        
        grid.add(new Label("账号:"), 0, 2);
        grid.add(accountField, 1, 2);
        grid.add(new Label("余额:"), 0, 3);
        grid.add(balanceField, 1, 3);
        grid.add(new Label("备注:"), 0, 4);
        grid.add(remarkArea, 1, 4);
        
        // 如果是修改，填充现有数据
        if (existingAsset != null) {
            typeCombo.setValue(existingAsset.getTypeName());
            nameField.setText(existingAsset.getName());
            accountField.setText(existingAsset.getAccountNumber());
            balanceField.setText(String.valueOf(existingAsset.getBalance()));
            remarkArea.setText(existingAsset.getRemark());
            
            if ("储蓄卡".equals(existingAsset.getTypeName()) || "信用卡".equals(existingAsset.getTypeName())) {
                bankCombo.setValue(existingAsset.getName());
            }
        } else {
            typeCombo.setValue("储蓄卡");  // 默认选择储蓄卡
        }
        
        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        
        // 触发一次类型选择事件以初始化布局
        typeCombo.fireEvent(new ActionEvent());
        
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == ButtonType.OK) {
                try {
                    Asset asset = existingAsset != null ? existingAsset : new Asset();
                    asset.setUserId(DatabaseManager.getUserId(currentUsername));
                    asset.setTypeName(typeCombo.getValue());
                    
                    if ("储蓄卡".equals(typeCombo.getValue()) || "信用卡".equals(typeCombo.getValue())) {
                        asset.setName(bankCombo.getValue());
                    } else {
                        asset.setName(typeCombo.getValue());
                    }
                    
                    asset.setAccountNumber(accountField.getText());
                    asset.setBalance(Double.parseDouble(balanceField.getText()));
                    asset.setRemark(remarkArea.getText());
                    asset.setCategory(getAssetCategory(typeCombo.getValue()));
                    return asset;
                } catch (Exception e) {
                    showError("输入错误", "请检查输入的数据格式是否正确。");
                    return null;
                }
            }
            return null;
        });
        
        return dialog;
    }

    private void refreshAssetTable(TableView<Asset> table) {
        int userId = DatabaseManager.getUserId(currentUsername);
        List<Asset> assets = DatabaseManager.getUserAssets(userId);
        table.setItems(FXCollections.observableArrayList(assets));
    }

    private void setupAssetTable(TableView<Asset> table) {
        // 类别列
        TableColumn<Asset, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        categoryCol.setPrefWidth(100);
        
        // 类型列
        TableColumn<Asset, String> typeCol = new TableColumn<>("类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("typeName"));
        typeCol.setPrefWidth(100);
        
        // 名称列
        TableColumn<Asset, String> nameCol = new TableColumn<>("名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameCol.setPrefWidth(150);
        
        // 账号列
        TableColumn<Asset, String> accountCol = new TableColumn<>("账号");
        accountCol.setCellValueFactory(new PropertyValueFactory<>("accountNumber"));
        accountCol.setPrefWidth(150);
        
        // 余额列
        TableColumn<Asset, Double> balanceCol = new TableColumn<>("余额");
        balanceCol.setCellValueFactory(new PropertyValueFactory<>("balance"));
        balanceCol.setPrefWidth(100);
        balanceCol.setCellFactory(col -> new TableCell<Asset, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                }
            }
        });
        
        table.getColumns().addAll(categoryCol, typeCol, nameCol, accountCol, balanceCol);
    }

    private String getAssetCategory(String type) {
        if (type.equals("储蓄卡") || type.equals("信用卡")) {
            return "银行账户";
        } else if (type.equals("余额宝") || type.equals("微信钱包") || type.equals("支付宝")) {
            return "网络支付";
        } else if (type.equals("花呗") || type.equals("京东白条")) {
            return "信用账户";
        } else if (type.equals("现金")) {
            return "现金";
        } else if (type.equals("理财产品") || type.equals("基金") || type.equals("股票")) {
            return "投资理财";
        } else if (type.equals("定期存款")) {
            return "定期理财";
        } else if (type.equals("公积金") || type.equals("养老保险") || type.equals("医疗保险")) {
            return "社保公积金";
        }
        return "其他";
    }

    private void deleteSelectedAsset(TableView<Asset> assetTable) {
        Asset selectedItem = assetTable.getSelectionModel().getSelectedItem();
        if (selectedItem == null) {
            showError("错误", "请选择要删除的资产");
            return;
        }

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除资产");
        alert.setContentText(String.format("确定要删除%s（余额：%.2f）吗？", 
            selectedItem.getName(), selectedItem.getBalance()));

        // 添加警告信息
        if (selectedItem.getBalance() > 0) {
            alert.getDialogPane().setExpandableContent(
                new Label("注意：该资产当前还有余额，删除后将无法恢复！"));
            alert.getDialogPane().setExpanded(true);
        }

        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                if (DatabaseManager.deleteAsset(selectedItem.getId())) {
                    refreshAssetTable(assetTable);
                    showInfo("删除成功", "资产已成功删除");
                } else {
                    showError("错误", "删除资产失败");
                }
            }
        });
    }

    // 1. 添加 isValidNumber 方法
    private boolean isValidNumber(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // 创建资产分布饼图 - 显示所有用户的资产
    private PieChart createAssetDistributionChart() {
        PieChart pieChart = new PieChart();
        
        // 按类别统计所有用户的资产
        Map<String, Double> categoryTotals = new HashMap<>();
        List<Asset> allAssets = DatabaseManager.getAllAssets();  // 使用获取所有资产的方法
        
        for (Asset asset : allAssets) {
            String category = asset.getCategory();
            double balance = asset.getBalance();
            categoryTotals.merge(category, balance, Double::sum);
        }
        
        // 添加数据
        categoryTotals.forEach((category, total) -> {
            PieChart.Data slice = new PieChart.Data(category, total);
            pieChart.getData().add(slice);
        });
        
        // 添加标签显示百分比
        pieChart.getData().forEach(data -> {
            double total = categoryTotals.values().stream().mapToDouble(Double::doubleValue).sum();
            String percentage = String.format("%.1f%%", (data.getPieValue() / total) * 100);
            Tooltip tooltip = new Tooltip(data.getName() + "\n" + 
                String.format("%.2f (占比: %s)", data.getPieValue(), percentage));
            Tooltip.install(data.getNode(), tooltip);
        });
        
        return pieChart;
    }

    // 创建资产趋势折线图 - 显示所有用户的资产趋势
    private LineChart<String, Number> createAssetTrendChart() {
        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis();
        LineChart<String, Number> lineChart = new LineChart<>(xAxis, yAxis);
        
        xAxis.setLabel("月份");
        yAxis.setLabel("金额");
        
        // 获取近6个月的资产趋势数据
        XYChart.Series<String, Number> series = new XYChart.Series<>();
        series.setName("总资产");
        
        // 从数据库获取所有用户的历史资产数据
        List<Map<String, Object>> trendData = DatabaseManager.getAllAssetTrendData(6);  // 新增方法
        
        trendData.forEach(data -> {
            series.getData().add(new XYChart.Data<>(
                data.get("month").toString(),
                (Number)data.get("total")
            ));
        });
        
        lineChart.getData().add(series);
        return lineChart;
    }

    // 设置资产概览表格
    private void setupAssetOverviewTable(TableView<Asset> table) {
        TableColumn<Asset, String> categoryCol = new TableColumn<>("类别");
        TableColumn<Asset, String> nameCol = new TableColumn<>("名称");
        TableColumn<Asset, Double> balanceCol = new TableColumn<>("余额");
        TableColumn<Asset, String> typeCol = new TableColumn<>("类型");
        
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        balanceCol.setCellValueFactory(new PropertyValueFactory<>("balance"));
        typeCol.setCellValueFactory(new PropertyValueFactory<>("typeName"));
        
        // 设置金额列的格式
        balanceCol.setCellFactory(col -> new TableCell<Asset, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                }
            }
        });
        
        table.getColumns().addAll(categoryCol, typeCol, nameCol, balanceCol);
        refreshAssetOverviewTable(table);
    }

    // 刷新资产概览表格
    private void refreshAssetOverviewTable(TableView<Asset> table) {
        int userId = DatabaseManager.getUserId(currentUsername);
        List<Asset> assets = DatabaseManager.getUserAssets(userId);
        table.setItems(FXCollections.observableArrayList(assets));
    }

    private void showFamilyAssetView() {
        VBox content = new VBox(20);
        content.setPadding(new Insets(30));
        content.getStyleClass().add("family-asset-view");
        
        // 1. 顶部标题和按钮区域
        HBox header = new HBox(20);
        header.setAlignment(Pos.CENTER_LEFT);
        
        Label titleLabel = new Label("家庭资产情况");
        titleLabel.getStyleClass().add("view-title");
        
        // 创建按钮组
        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        HBox.setHgrow(buttonBox, Priority.ALWAYS);
        
        Button snapshotBtn = new Button("创建快照");
        Button historyBtn = new Button("历史快照");
        snapshotBtn.getStyleClass().addAll("primary-button", "icon-button");
        historyBtn.getStyleClass().addAll("secondary-button", "icon-button");
        
        buttonBox.getChildren().addAll(snapshotBtn, historyBtn);
        header.getChildren().addAll(titleLabel, buttonBox);
        
        // 2. 总资产统计卡片区域
        ScrollPane statsScroll = new ScrollPane();
        statsScroll.setFitToWidth(true);
        statsScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        statsScroll.getStyleClass().add("stats-scroll");
        
        HBox statsCards = new HBox(20);
        statsCards.setAlignment(Pos.CENTER_LEFT);
        statsCards.setPadding(new Insets(10));
        
        // 获取所有资产数据
        List<Asset> allAssets = DatabaseManager.getAllAssets();
        
        // 计算总资产
        double totalAssets = allAssets.stream()
            .mapToDouble(Asset::getBalance)
            .sum();
        
        // 按类别统计资产
        Map<String, Double> categoryTotals = allAssets.stream()
            .collect(Collectors.groupingBy(
                Asset::getCategory,
                Collectors.summingDouble(Asset::getBalance)
            ));
        
        // 创建总资产卡片
        VBox totalCard = createStatsCard("总资产", String.format("¥%.2f", totalAssets), "total-card");
        statsCards.getChildren().add(totalCard);
        
        // 为每个类别创建统计卡片
        categoryTotals.forEach((category, amount) -> {
            VBox categoryCard = createStatsCard(
                category, 
                String.format("¥%.2f", amount),
                "category-card"
            );
            statsCards.getChildren().add(categoryCard);
        });
        
        statsScroll.setContent(statsCards);
        
        // 3. 图表区域
        HBox chartsBox = new HBox(30);
        chartsBox.setAlignment(Pos.CENTER);
        chartsBox.setPadding(new Insets(20));
        chartsBox.getStyleClass().add("charts-container");
        
        // 创建饼图
        PieChart distributionChart = createAssetDistributionChart();
        distributionChart.setTitle("资产分布");
        distributionChart.setPrefSize(400, 300);
        
        // 创建折线图
        LineChart<String, Number> trendChart = createAssetTrendChart();
        trendChart.setTitle("资产趋势");
        trendChart.setPrefSize(400, 300);
        
        chartsBox.getChildren().addAll(distributionChart, trendChart);
        
        // 4. 资产明细表格
        TableView<Asset> assetTable = new TableView<>();
        assetTable.getStyleClass().add("asset-table");
        
        // 用户列
        TableColumn<Asset, String> userCol = new TableColumn<>("所属用户");
        userCol.setCellValueFactory(new PropertyValueFactory<>("userName"));
        userCol.setPrefWidth(100);
        
        // 类别列
        TableColumn<Asset, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        categoryCol.setPrefWidth(100);
        
        // 类型列
        TableColumn<Asset, String> typeCol = new TableColumn<>("类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("typeName"));
        typeCol.setPrefWidth(100);
        
        // 名称列
        TableColumn<Asset, String> nameCol = new TableColumn<>("名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameCol.setPrefWidth(150);
        
        // 账号列
        TableColumn<Asset, String> accountCol = new TableColumn<>("账号");
        accountCol.setCellValueFactory(new PropertyValueFactory<>("accountNumber"));
        accountCol.setPrefWidth(150);
        
        // 余额列
        TableColumn<Asset, Double> balanceCol = new TableColumn<>("余额");
        balanceCol.setCellValueFactory(new PropertyValueFactory<>("balance"));
        balanceCol.setPrefWidth(100);
        balanceCol.setCellFactory(col -> new TableCell<Asset, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                }
            }
        });
        
        assetTable.getColumns().addAll(userCol, categoryCol, typeCol, nameCol, accountCol, balanceCol);
        assetTable.setItems(FXCollections.observableArrayList(allAssets));
        VBox.setVgrow(assetTable, Priority.ALWAYS);
        
        // 设置事件处理
        snapshotBtn.setOnAction(e -> createSnapshot());
        historyBtn.setOnAction(e -> showSnapshotHistory());
        
        // 将所有内容添加到主容器
        content.getChildren().addAll(header, statsScroll, chartsBox, assetTable);
        root.setCenter(content);
    }

    // 创建快照
    private void createSnapshot() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("创建资产快照");
        dialog.setHeaderText("请输入快照描述");
        dialog.setContentText("描述:");

        dialog.showAndWait().ifPresent(description -> {
            if (DatabaseManager.createAssetSnapshot(description)) {
                showInfo("成功", "资产快照创建成功");
            } else {
                showError("错误", "创建快照失败");
            }
        });
    }

    // 显示快照历史
    private void showSnapshotHistory() {
        Stage stage = new Stage();
        stage.setTitle("资产快照历史");
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 创建快照列表
        ListView<AssetSnapshot> snapshotList = new ListView<>();
        snapshotList.setCellFactory(lv -> new ListCell<AssetSnapshot>() {
            @Override
            protected void updateItem(AssetSnapshot snapshot, boolean empty) {
                super.updateItem(snapshot, empty);
                if (empty || snapshot == null) {
                    setText(null);
                } else {
                    setText(String.format("%s - 总资产: ¥%.2f\n%s",
                        snapshot.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                        snapshot.getTotalAssets(),
                        snapshot.getDescription()
                    ));
                }
            }
        });
        
        // 加载快照数据
        List<AssetSnapshot> snapshots = DatabaseManager.getAllSnapshots();
        snapshotList.setItems(FXCollections.observableArrayList(snapshots));
        
        // 添加查看详情功能
        snapshotList.setOnMouseClicked(e -> {
            if (e.getClickCount() == 2) {
                AssetSnapshot selected = snapshotList.getSelectionModel().getSelectedItem();
                if (selected != null) {
                    showSnapshotDetails(selected);
                }
            }
        });
        
        content.getChildren().add(snapshotList);
        
        Scene scene = new Scene(content, 600, 400);
        stage.setScene(scene);
        stage.show();
    }

    // 显示快照详情
    private void showSnapshotDetails(AssetSnapshot snapshot) {
        Stage stage = new Stage();
        stage.setTitle("快照详情 - " + 
            snapshot.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));
        
        // 显示总资产和描述
        Label totalLabel = new Label(String.format("总资产: ¥%.2f", snapshot.getTotalAssets()));
        Label descLabel = new Label("描述: " + snapshot.getDescription());
        
        // 显示类别统计
        HBox statsCards = new HBox(20);
        statsCards.setAlignment(Pos.CENTER);
        
        for (CategoryTotal categoryTotal : snapshot.getCategoryTotals()) {
            VBox card = createStatsCard(
                categoryTotal.getCategory(),
                String.format("¥%.2f", categoryTotal.getTotal()),
                "category-card"
            );
            statsCards.getChildren().add(card);
        }
        
        // 显示资产详情表格
        TableView<AssetSnapshotDetail> detailTable = new TableView<>();
        
        // 添加列
        TableColumn<AssetSnapshotDetail, String> userCol = new TableColumn<>("用户");
        userCol.setCellValueFactory(new PropertyValueFactory<>("userName"));
        
        TableColumn<AssetSnapshotDetail, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));
        
        TableColumn<AssetSnapshotDetail, String> typeCol = new TableColumn<>("类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("typeName"));
        
        TableColumn<AssetSnapshotDetail, String> nameCol = new TableColumn<>("名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        
        TableColumn<AssetSnapshotDetail, String> accountCol = new TableColumn<>("账号");
        accountCol.setCellValueFactory(new PropertyValueFactory<>("accountNumber"));
        
        TableColumn<AssetSnapshotDetail, Double> balanceCol = new TableColumn<>("余额");
        balanceCol.setCellValueFactory(new PropertyValueFactory<>("balance"));
        balanceCol.setCellFactory(col -> new TableCell<AssetSnapshotDetail, Double>() {
            @Override
            protected void updateItem(Double amount, boolean empty) {
                super.updateItem(amount, empty);
                if (empty || amount == null) {
                    setText(null);
                } else {
                    setText(String.format("%.2f", amount));
                }
            }
        });
        
        detailTable.getColumns().addAll(
            userCol, categoryCol, typeCol, nameCol, accountCol, balanceCol
        );
        
        detailTable.setItems(FXCollections.observableArrayList(snapshot.getDetails()));
        
        content.getChildren().addAll(totalLabel, descLabel, statsCards, detailTable);
        
        Scene scene = new Scene(content, 800, 600);
        stage.setScene(scene);
        stage.show();
    }
} 